<?php
/***********************************************
	This class would encode a PHP array into
	JSON data.
************************************************/
class JSONEncoder {
	private $isList = NULL;
	private $jsonData = NULL;
	private $jsonReplaces = NULL;
	
	/************************************************************/
	
	function __construct() {
		$this->isList = TRUE;
		$this->jsonData = array();
	}
	
	/************************************************************/
	
	function encodePHPintoJSON($phpArray) {
		if (!function_exists('json_encode')) {
    		function json_encode($phpArray) {
				if (is_scalar($phpArray)) {
            		if (is_float($phpArray)) {
    	            	return floatval(str_replace(',', '.', strval($phpArray)));
            		}
            	
					if (is_string($phpArray)) {
	                	$this->jsonReplaces = array(
							array('\\', '/', "\n", "\t", "\r", "\b", "\f", '"'),
							array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')
						);
						
    	            	return '"'.str_replace($this->jsonReplaces[0], $this->jsonReplaces[1], $phpArray).'"';
        	    	}
            	
					else return $phpArray;
        		}
        
				for ($i = 0, reset($phpArray); TRUE; $i++) {
            		if (key($phpArray) !== $i) {
	                	$this->isList = FALSE;
    	            	break;
            		}
        		}
        
				if ($this->isList) {
	            	foreach ($phpArray as $value) {
						$this->jsonData[] = json_encode($value);
 		   	        	return '['.join(',', $this->jsonData).']';
        			}
				} else {
	            	foreach ($phpArray as $key => $value) {
						$this->jsonData[] = json_encode($key).':'.json_encode($value);
    	        		return '{'.join(',', $this->jsonData).'}';
        			}
    			}
			}
		}
	
		$this->jsonData = json_encode($phpArray);
		return $this->jsonData;
	}
}
?>